package com.garrett.demo.sys.dao;

import com.garrett.demo.sys.entity.Account;
import com.garrett.demo.sys.entity.SimsStudent;

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class UserDaoTextImp implements UserDao {
    // ... 其他代码片段

    /**
     * 添加学生信息
     */
    @Override
    public int createUser(SimsStudent userInfo) {
        UserDaoTextImp s=new UserDaoTextImp();
        String path1 = "./211805142/src/com/garrett/demo/sys/dao/sims_student.txt";
        File file1 = new File(path1);
        OutputStreamWriter osw1 = null;
        if (!file1.exists()) {
            System.out.println("数据源不存在!!!");
            throw new RuntimeException("数据源不存在");
        }
        try {// 创建基于文件的输出流
            FileOutputStream fos = new FileOutputStream(file1, true);
            // 指定编码格式，以免读取时中文字符异常
            osw1 = new OutputStreamWriter(fos, "UTF-8");
                osw1.write(userInfo.toString()+"\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw1) {
                try {
                    osw1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }

    @Override
    public int delStudentInfo(String stuId) {
        UserDaoTextImp s=new UserDaoTextImp();
        SimsStudent[] b=new SimsStudent[100];
        int index = 0;
        int count=0;
        for (int i = 0; i <s.count(); i++) {
            if(s.getStudent()[i].getStudentId().equals(stuId)){
                index=i;
            }
        }
        for (int i = 0,j=0; i <s.count() ; i++) {
            if(i!=index){
                b[j]=s.getStudent()[i];
                j++;
                count++;
            }
        }
        String path1 = "./211805142/src/com/garrett/demo/sys/dao/sims_student.txt";
        File file1 = new File(path1);
        OutputStreamWriter osw1 = null;
        if (!file1.exists()) {
            System.out.println("数据源不存在!!!");
            throw new RuntimeException("数据源不存在");
        }
        try {// 创建基于文件的输出流
            FileOutputStream fos = new FileOutputStream(file1, false);
            // 指定编码格式，以免读取时中文字符异常
            osw1 = new OutputStreamWriter(fos, "UTF-8");
            osw1.write("");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw1) {
                try {
                    osw1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String path2 = "./211805142/src/com/garrett/demo/sys/dao/sims_student.txt";
        File file2 = new File(path2);
        OutputStreamWriter osw2 = osw1;
        if (!file2.exists()) {
            System.out.println("数据源不存在!!!");
            throw new RuntimeException("数据源不存在");
        }
        try {// 创建基于文件的输出流
            FileOutputStream fos = new FileOutputStream(file1, true);
            // 指定编码格式，以免读取时中文字符异常
            osw2 = new OutputStreamWriter(fos, "UTF-8");
            for (int i = 0; i <count; i++) {
                osw2.write(b[i].toString() + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw2) {
                try {
                    osw2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }

    @Override
    public int modifyStudentInfo(SimsStudent student) {
        Scanner sc = new Scanner(System.in);
        UserDaoTextImp s = new UserDaoTextImp();
        SimsStudent[] b = new SimsStudent[100];
        int index = 0;
        int count=s.count();
        System.out.println("1、学号");
        System.out.println("2、姓名");
        System.out.println("3、英文名");
        System.out.println("4、身份证号");
        System.out.println("5、手机号");
        System.out.println("6、性别");
        System.out.println("7、身高");
        System.out.println("8、体重");
        System.out.println("9、民族");
        System.out.println("10、政治面貌");
        System.out.println("11、电子邮件");
        for (int i = 0; i < s.count(); i++) {
            b[i] = s.getStudent()[i];
        }
        for (int i = 0; i < s.count(); i++) {
            if (b[i].getStudentId().equals(student.getStudentId())) {
                index = i;
            }
        }
        System.out.println(b[index]);
        System.out.print("请输入要修改的选项：");
        String n = sc.nextLine();
        if (n.equals("1")) {
            System.out.print("请输入新的学号：");
            String studentId = sc.nextLine();
            b[index].setStudentId(studentId);
        } else if (n.equals("2")) {
            System.out.print("请输入新的姓名：");
            String studentName = sc.nextLine();
            b[index].setStudentName(studentName);
        } else if (n.equals("3")) {
            System.out.print("请输入新的英文名：");
            String engName = sc.nextLine();
            b[index].setEngName(engName);
        } else if (n.equals("4")) {
            System.out.print("请输入新的身份证号：");
            String idCardNo = sc.nextLine();
            b[index].setIdCardNo(idCardNo);
        } else if (n.equals("5")) {
            System.out.print("请输入新的手机号：");
            String mobilePhone = sc.nextLine();
            b[index].setMobilePhone(mobilePhone);
        } else if (n.equals("6")) {
            System.out.print("请输入新的性别：");
            String gender = sc.nextLine();
            b[index].setGender(gender);
        } else if (n.equals("7")) {
            System.out.print("请输入新的身高：");
            String height = sc.nextLine();
            b[index].setHeight(height);
        } else if (n.equals("8")) {
            System.out.print("请输入新的体重：");
            String weight = sc.nextLine();
            b[index].setWeight(weight);
        } else if (n.equals("9")) {
            System.out.print("请输入新的民族：");
            String nation = sc.nextLine();
            b[index].setNation(nation);
        } else if (n.equals("10")) {
            System.out.print("请输入新的政治面貌：");
            String political = sc.nextLine();
            b[index].setPolitical(political);
        } else if (n.equals("11")) {
            System.out.print("请输入新的电子邮件：");
            String email = sc.nextLine();
            b[index].setEmail(email);
        }
        String path1 = "./211805142/src/com/garrett/demo/sys/dao/sims_student.txt";
        File file1 = new File(path1);
        OutputStreamWriter osw1 = null;
        if (!file1.exists()) {
            System.out.println("数据源不存在!!!");
            throw new RuntimeException("数据源不存在");
        }
        try {// 创建基于文件的输出流
            FileOutputStream fos = new FileOutputStream(file1, false);
            // 指定编码格式，以免读取时中文字符异常
            osw1 = new OutputStreamWriter(fos, "UTF-8");
            osw1.write("");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw1) {
                try {
                    osw1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String path2 = "./211805142/src/com/garrett/demo/sys/dao/sims_student.txt";
        File file2 = new File(path2);
        OutputStreamWriter osw2 = osw1;
        if (!file2.exists()) {
            System.out.println("数据源不存在!!!");
            throw new RuntimeException("数据源不存在");
        }
        try {// 创建基于文件的输出流
            FileOutputStream fos = new FileOutputStream(file1, true);
            // 指定编码格式，以免读取时中文字符异常
            osw2 = new OutputStreamWriter(fos, "UTF-8");
            for (int i = 0; i < count; i++) {
                    osw2.write(b[i].toString()+"\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw2) {
                try {
                    osw2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(b[index]);
        return 0;
    }

    @Override
    public SimsStudent[] getAllStudent() {
        UserDaoTextImp s=new UserDaoTextImp();
        SimsStudent[] b=new SimsStudent[100];
        for (int i = 0; i <s.count(); i++) {
            b[i]=s.getStudent()[i];
        }
        return b;
    }

    /**
     * 根据用户编号获取用户信息
     *
     * @return
     */
    @Override
    public SimsStudent getStudentById(String stuId) {
        String path = "./211805142/src/com/garrett/demo/sys/dao/sims_student.txt";
        File file = new File(path);
        try {
            if (file.isFile() && file.exists()) {
                //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                //考虑到编码格式B
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    SimsStudent stu = recordFormat(lineTxt);
                    if (stu.getStudentId().equals(stuId)) return stu;
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 单行数据记录处理
     *
     * @param row 行记录
     * @return 学生信息
     */
    SimsStudent recordFormat(String row) {
        SimsStudent stu = null;
        int beginIndex = row.indexOf("{") + 1;
        int endIndex = row.indexOf("}");
        String content = row.substring(beginIndex, endIndex);
        String[] split = content.split(",");
        String[] fields = Arrays.stream(split).map(String::trim).toArray(String[]::new);
        if (fields.length > 0) {
            stu = new SimsStudent();
            stu.setClassId(fields[0]);
            stu.setStudentId(fields[1]);
            stu.setStudentName(fields[2]);
            stu.setEngName(fields[3]);
            stu.setIdCardNo(fields[4]);
            stu.setMobilePhone(fields[5]);
            stu.setGender(fields[6]);
            stu.setHeight(fields[7]);
            stu.setWeight(fields[8]);
            stu.setNation(fields[9]);
            stu.setPolitical(fields[10]);
            stu.setEmail(fields[17]);
        }
        return stu;
    }
    Account recordFormat1(String row) {
        Account stu = null;
        int beginIndex = row.indexOf("{") + 1;
        int endIndex = row.indexOf("}");
        String content = row.substring(beginIndex, endIndex);
        String[] split = content.split(",");
        String[] fields = Arrays.stream(split).map(String::trim).toArray(String[]::new);
        if (fields.length > 0) {
            stu = new Account();
            stu.setId(fields[0]);
            stu.setAccount(fields[1]);
            stu.setPassword(fields[2]);
        }
        return stu;
    }

    @Override
    public int addAccount(Account account) {
        OutputStreamWriter osw1 = null;
        UserDaoTextImp s=new UserDaoTextImp();
        String path2 = "./211805142/src/com/garrett/demo/sys/dao/sims_accounts.txt";
        File file2 = new File(path2);
        OutputStreamWriter osw2 = null;
        if (!file2.exists()) {
            System.out.println("数据源不存在!!!");
            throw new RuntimeException("数据源不存在");
        }
        try {// 创建基于文件的输出流
            FileOutputStream fos = new FileOutputStream(file2, true);
            // 指定编码格式，以免读取时中文字符异常
            osw1 = new OutputStreamWriter(fos, "UTF-8");
                osw1.write("{"+String.format("%d",s.count())+","+account.getAccount()+","+account.getPassword() + "}"+"\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw1) {
                try {
                    osw1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }

    @Override
    public int delAccountById(String id) {
        UserDaoTextImp s=new UserDaoTextImp();
        Account[] b=new Account[100];
        int index = Integer.parseInt(id)-1;
        int count=0;
        for (int i = 0,j=0; i <=s.count() ; i++) {
            if(i!=index){
                b[j]=s.getAccount()[i];
                j++;
                count++;
            }
        }
        String path1 = "./211805142/src/com/garrett/demo/sys/dao/sims_accounts.txt";
        File file1 = new File(path1);
        OutputStreamWriter osw1 = null;
        if (!file1.exists()) {
            System.out.println("数据源不存在!!!");
            throw new RuntimeException("数据源不存在");
        }
        try {// 创建基于文件的输出流
            FileOutputStream fos = new FileOutputStream(file1, false);
            // 指定编码格式，以免读取时中文字符异常
            osw1 = new OutputStreamWriter(fos, "UTF-8");
            osw1.write("");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw1) {
                try {
                    osw1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String path2 = "./211805142/src/com/garrett/demo/sys/dao/sims_accounts.txt";
        File file2 = new File(path2);
        OutputStreamWriter osw2 = osw1;
        if (!file2.exists()) {
            System.out.println("数据源不存在!!!");
            throw new RuntimeException("数据源不存在");
        }
        try {// 创建基于文件的输出流
            FileOutputStream fos = new FileOutputStream(file1, true);
            // 指定编码格式，以免读取时中文字符异常
            osw2 = new OutputStreamWriter(fos, "UTF-8");
            for (int i = 0; i <count; i++) {
                osw2.write("{"+String.format("%d",i+1)+","+b[i].getAccount()+","+b[i].getPassword() + "}"+ "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw2) {
                try {
                    osw2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }

    @Override
    public int modifyAccount(Account account) {
        Scanner sc = new Scanner(System.in);
        UserDaoTextImp s = new UserDaoTextImp();
        Account[] b = new Account[100];
        int index=0;
        int count=s.count();
        System.out.println("1、编号");
        System.out.println("2、账户名");
        System.out.println("3、密码");
        for (int i = 0; i <s.count(); i++) {
            b[i]=s.getAccount()[i];
        }
        for (int i = 0; i <s.count() ; i++) {
            if(b[i].getAccount().equals(account.getAccount())){
                index=i;
            }
        }
        System.out.print("请输入要修改的选项：");
       String n = sc.nextLine();
        if (n.equals("1")) {
            System.out.print("请输入新的编号：");
            String id = sc.nextLine();
            b[index].setId(id);
        } else if (n.equals("2")) {
            System.out.print("请输入新的账户名：");
            String accounts = sc.nextLine();
           b[index].setAccount(accounts);
        } else if (n.equals("3")) {
            System.out.print("请输入新的密码：");
            String passsword = sc.nextLine();
            b[index].setPassword(passsword);
            String path1 = "./211805142/src/com/garrett/demo/sys/dao/sims_accounts.txt";
            File file1 = new File(path1);
            OutputStreamWriter osw1 = null;
            if (!file1.exists()) {
                System.out.println("数据源不存在!!!");
                throw new RuntimeException("数据源不存在");
            }
            try {// 创建基于文件的输出流
                FileOutputStream fos = new FileOutputStream(file1, false);
                // 指定编码格式，以免读取时中文字符异常
                osw1 = new OutputStreamWriter(fos, "UTF-8");
                osw1.write("");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != osw1) {
                    try {
                        osw1.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            String path2 = "./211805142/src/com/garrett/demo/sys/dao/sims_accounts.txt";
            File file2 = new File(path2);
            OutputStreamWriter osw2 = osw1;
            if (!file2.exists()) {
                System.out.println("数据源不存在!!!");
                throw new RuntimeException("数据源不存在");
            }
            try {// 创建基于文件的输出流
                FileOutputStream fos = new FileOutputStream(file1, true);
                // 指定编码格式，以免读取时中文字符异常
                osw2 = new OutputStreamWriter(fos, "UTF-8");
                for (int i = 0; i < count; i++) {
                        osw2.write("{"+String.format("%d",i+1)+","+b[i].getAccount()+","+b[i].getPassword() + "}"+ "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != osw2) {
                    try {
                        osw2.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return 0;
    }

    @Override
    public Account getUserByAccount(String account) {
        String path = "./211805142/src/com/garrett/demo/sys/dao/sims_accounts.txt";
        File file = new File(path);
        try {
            if (file.isFile() && file.exists()) {
                //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                //考虑到编码格式B
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    Account stu = recordFormat1(lineTxt);
                    if (stu.getAccount().equals(account)) return stu;
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return null;
    }

    public SimsStudent[] getStudent() {
        int count = 0;
        SimsStudent[] students = new SimsStudent[100];
        String path = "./211805142/src/com/garrett/demo/sys/dao/sims_student.txt";
        File file = new File(path);
        try {
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    SimsStudent stu = recordFormat(lineTxt);
                    students[count++] = stu;
                }
            }
        } catch (Exception e) {
            return null;
        }
        return students;
    }
    public Account[] getAccount(){
        int count = 0;
        Account[] accounts = new Account[100];
        String path = "./211805142/src/com/garrett/demo/sys/dao/sims_accounts.txt";
        File file = new File(path);
        try {
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    Account stu = recordFormat1(lineTxt);
                   accounts[count++] = stu;
                }
            }
        } catch (Exception e) {
            return null;
        }
        return accounts;
    }
    public int count(){
        int count = 0;
        SimsStudent[] students = new SimsStudent[100];
        String path = "./211805142/src/com/garrett/demo/sys/dao/sims_student.txt";
        File file = new File(path);
        try {
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    count++;
                }
            }
        } catch (Exception e) {
            return 0;
        }
        return count;
    }
}